<?php

// 充值功能

namespace app\shop\controller;

use think\Db;
use think\Session;
use think\Request;
use think\Controller;
use app\shop\model\Member as MemberModel;
use app\shop\model\MemberWithdraw as MemberWithdrawModel;

class Recharge extends Controller
{
    public function index()
    {
        // 获取会员ID
        $memberId = Session::get('member_id');

        // 获取用户信息
        $find = (new MemberModel())->where(['id' => $memberId])->find();

        if (Request::instance()->isPost()) {
            // 获取参数
            $data = Request::instance()->param();

            // 充值金额大于一元
            if ($data['price'] <= 0) return ['code' => 402, 'message' => '充值金额必须大于一元'];

            // 启动事务
            Db::startTrans();

            try {

                // 生成订单号
                $order_number = $this->createNumber();


                return ['code' => 200, 'order_number' => $order_number, 'user_id' => $memberId,'price'=>$data['price']];
            } catch (\Exception $e) {

                // 回滚事务
                Db::rollback();

                return ['code' => 401, 'message' => '网络繁忙'];
            }
        }


        return $this->fetch('', [
            'mate_head' => ' 我的钱包-充值',
            'find'    => $find

        ]);
    }


    /**
     * 生成订单号
     */
    protected function createNumber()
    {
        //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）
        $order_id_main = date('YmdHis') . rand(10000000, 99999999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
        $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);

        return $order_id;
    }
}